package com.yl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.dao.TActivityMapper;
import com.yl.mode2.TActOrder2;
import com.yl.model.TActOrder;
import com.yl.dao.TActOrderMapper;
import com.yl.model.TActivity;
import com.yl.pay.UnionPay;
import com.yl.pay.WxPay;
import com.yl.result.APIException;
import com.yl.service.TActOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yl.utils.UnionPayUtil;
import com.yl.utils.Utils;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lfs
 * @since 2020-11-30
 */
@Service
@Log
public class TActOrderServiceImpl extends ServiceImpl<TActOrderMapper, TActOrder> implements TActOrderService {

    @Autowired
    UnionPay unionPay;
    @Autowired
    WxPay wxPay;
    @Autowired
    TActOrderMapper mapper;

    @Autowired
    TActivityMapper actMapper;

    /**
     * 银联支付1块钱换水
     * @param orderId
     * @return
     */
    public String unionPay(String orderId) {
        TActOrder order=mapper.selectById(orderId);
        try {
            if(order == null)
                throw new APIException("支付异常：未生成订单号");
           return unionPay.publicPay(order.getMOrderId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new APIException("支付异常");
        }
    }

    /**
     * 银联微信支付
     * @param orderId  订单ID
     * @param actId 活动ID
     * @return
     */
    public String wxPay(String orderId,String actId) {
        TActOrder order = mapper.selectById(orderId);
        TActivity activity = actMapper.selectById(actId);
        try {
            if(activity == null)
                throw new APIException("支付异常：不存在此活动！");
            if(order == null)
                throw new APIException("支付异常：未生成订单号！");
            if(activity.getAmount() == null || new Double(String.valueOf(activity.getAmount())).doubleValue() == 0D)
                throw new APIException("支付异常：此活动未设置价格！");
            return wxPay.publicPay(order.getMOrderId(),String.valueOf(activity.getAmount()),activity.getActName());
        } catch (Exception e) {
            e.printStackTrace();
            throw new APIException("支付异常");
        }
    }

    /**
     * 创建订单
     * @param mobile
     * @param userId
     * @return
     */
    public TActOrder createOrder(Long userId,String name,String mobile) {
        String mOrderId = UnionPayUtil.genMerOrderId(unionPay.getMsgSrcId());
        TActOrder tActOrder = new TActOrder();
        tActOrder.setAmount(new BigDecimal(1));
        tActOrder.setMOrderId(mOrderId);
        tActOrder.setMobile(mobile);
        tActOrder.setActId(Long.parseLong(1+""));
        tActOrder.setPayType(0);
        tActOrder.setClientId(userId);
        tActOrder.setCustomerName(name);
        tActOrder.setMobile(mobile);
        mapper.insert(tActOrder);
        return tActOrder;
    }

    public TActOrder createOrder(TActOrder2 tActOrder2) {
        String mOrderId = UnionPayUtil.genMerOrderId(unionPay.getMsgSrcId());
        TActOrder tActOrder = new TActOrder();
        tActOrder.setAmount(new BigDecimal(1));
        tActOrder.setMOrderId(mOrderId);
        tActOrder.setMobile(tActOrder2.getMobile());
        if(tActOrder2.getActId() != 0)
            tActOrder.setActId(tActOrder2.getActId());
        else
            tActOrder.setActId(Long.parseLong(1+""));
        tActOrder.setPayType(Integer.parseInt(String.valueOf(tActOrder2.getPayType())));
        tActOrder.setCustomerName(tActOrder2.getCustomerName());
        tActOrder.setMobile(tActOrder2.getMobile());
        if(tActOrder2.getOpenId() != null)
            tActOrder.setOpenId(tActOrder2.getOpenId());
        if(tActOrder2.getUnionId() != null)
            tActOrder.setUnionId(tActOrder2.getUnionId());
        if(tActOrder2.getLatitude() != null)
            tActOrder.setLatitude(tActOrder2.getLatitude());
        if(tActOrder2.getLongitude() != null)
            tActOrder.setLongitude(tActOrder2.getLongitude());
        if(tActOrder2.getPosNo() != null)
            tActOrder.setPosNo(tActOrder2.getPosNo());
        if(tActOrder2.getTermNo() != null)
            tActOrder.setTermNo(tActOrder2.getTermNo());
        if(tActOrder2.getSchool() != null)
            tActOrder.setSchool(tActOrder2.getSchool());
        if(tActOrder2.getGrade() != null)
            tActOrder.setGrade(tActOrder2.getGrade());
        if(tActOrder2.getClassName() != null)
            tActOrder.setClassName(tActOrder2.getClassName());
        if(tActOrder2.getPrice() != 0)
            tActOrder.setPrice(new BigDecimal(tActOrder2.getPrice()));
        if(tActOrder2.getNumber() != 0)
            tActOrder.setNumber(new Integer(String.valueOf(tActOrder2.getNumber())));
        if(tActOrder2.getSpec() != null)
            tActOrder.setSpec(tActOrder2.getSpec());
        if(tActOrder2.getUnit() != null)
            tActOrder.setUnit(tActOrder2.getUnit());
        if(tActOrder2.getUnionOrderNo() != null)
            tActOrder.setUnionOrderNo(tActOrder2.getUnionOrderNo());
        if(tActOrder2.getEnterpriseId() != 0)
            tActOrder.setEnterpriseId(tActOrder2.getEnterpriseId());
        if(tActOrder2.getRegion() != null)
            tActOrder.setRegion(tActOrder2.getRegion());
        if(tActOrder2.getAddress() != null)
            tActOrder.setAddress(tActOrder2.getAddress());
        if(tActOrder2.getPostCode() != null)
            tActOrder.setPostCode(tActOrder2.getPostCode());
        log.info("#### createOrder getTakeTicketDate = " + tActOrder2.getTakeTicketDate());
        if(tActOrder2.getTakeTicketDate() != null && tActOrder2.getTakeTicketDate().indexOf("-")>0) {
            LocalDate pTime = Utils.formatDate(tActOrder2.getTakeTicketDate());
            log.info("#### createOrder pTime = " + pTime);
            if(pTime != null)
                tActOrder.setTakeTicketDate(pTime);
        }
        log.info("#### createOrder getCouponAmount = " + tActOrder2.getCouponAmount());
        if(tActOrder2.getCouponAmount() != null)
            tActOrder.setCouponAmount(new BigDecimal(tActOrder2.getCouponAmount()));
        if(tActOrder2.getEnterpriseId() != 0)
            tActOrder.setEnterpriseId(tActOrder2.getEnterpriseId());

        //log.info("#### mobile: " + tActOrder.getMobile());

        mapper.insert(tActOrder);
        return tActOrder;
    }

    /**
     * 创建订单
     * @param mobile
     * @param name
     * @return
     */
    public TActOrder createOrder(String name,String mobile) {
        String mOrderId = UnionPayUtil.genMerOrderId(unionPay.getMsgSrcId());
        TActOrder tActOrder = new TActOrder();
        tActOrder.setAmount(new BigDecimal(1));
        tActOrder.setMOrderId(mOrderId);
        tActOrder.setMobile(mobile);
        tActOrder.setActId(Long.parseLong(1+""));
        tActOrder.setPayType(0);
        tActOrder.setCustomerName(name);
        tActOrder.setMobile(mobile);
        mapper.insert(tActOrder);
        return tActOrder;
    }

    public TActOrder findTActOrder(String mobile) {
        return mapper.findOrderByMobile(mobile);
    }
    /**
     * 订单支付成功 -用户回调修改订单状态
     * @param mOrderId
     */
    public void orderPaySucceed(String mOrderId) {
        TActOrder order = mapper.findOrderByMOrderId(mOrderId);
        if(order!=null) {
            order.setPayType(1);
            //order.setUnionOrderNo("");
            Boolean update = order.updateById();
        }
    }

    public static BigDecimal formatBigDecimal(BigDecimal data) {
        if (data == null)
            return data;
        return data.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public void orderPaySucceed(Map<String, String> mapData) throws Exception{
        /*
            payTime=2020-12-17 18:54:10, buyerCashPayAmt=1, connectSys=ORIGINAL, sign=AC68F7C76C13AFE0076158E029EE5F540A6241EA1A80444057B5CB3F8B28F11C,
             merName=广西由来溯往云数据科技有限责任公司, mid=898450173750102, invoiceAmount=1, secureStatus=UNCOMPLETED, settleDate=2020-12-17,
              billFunds=现金:1|优惠:1, mchntUuid=2d9081bd756ad12e0175727b83ca07c8, tid=20219232, instMid=H5DEFAULT, receiptAmount=2, couponAmount=1,
              targetOrderId=262012171854108140448, signType=SHA256, billFundsDesc=现金支付0.01元，优惠支付0.01元。, orderDesc=广西由来溯往云数据科技有限责任公司,
               seqId=18855499989N, merOrderId=10XF202012171854028558736080, targetSys=UAC, bankCardNo=621700*********6589, Hw=lZrl, totalAmount=2,
               couponMerchantContribute=0, createTime=2020-12-17 18:54:10, buyerPayAmount=1, goodsTradeNo=1000202012171854109993398202, couponOtherContribute=1,
                notifyId=d356eaca-e8b4-40fa-ba6a-0ea6df02a61e, subInst=103000, status=TRADE_SUCCESS
         */
        String mOrderId = mapData.get("merOrderId");
        TActOrder order = mapper.findOrderByMOrderId(mOrderId);
        if(order != null) {
            order.setPayType(1);//云闪付
            LocalDateTime pTime = Utils.formatDateTime(mapData.get("payTime"));
            if(pTime != null)
                order.setPayTime(pTime);//支付时间
            order.setUnionOrderNo(mapData.get("goodsTradeNo"));//银联订单号
            order.setPosNo(mapData.get("mid"));//商户号
            order.setTermNo(mapData.get("tid"));//终端号
            //order.setPrice(formatDecimalToString(mapData.get("totalAmount")));
            order.setAmount(formatDecimalToString(mapData.get("buyerPayAmount")));
            order.setOrStatus(mapData.get("status"));
            order.setBillDesc(mapData.get("billFundsDesc"));
            order.setBankCardNo(mapData.get("bankCardNo"));
            Boolean update = order.updateById();
        }else{
            throw new APIException("订单号：" + mOrderId + " 不存在！");
        }
    }

    public BigDecimal formatDecimalToString(String data) {
        BigDecimal b = new BigDecimal(new Double(data)/100D);
        return new BigDecimal(Double.valueOf(String.valueOf(b.setScale(2, BigDecimal.ROUND_HALF_UP))));
    }



    public List<TActOrder> getOrderList(String userId,Integer type) {
        return mapper.findOrderByUserId(userId,type);
    }

    public IPage<TActOrder> getOrderListByUserAndType(String userId, Integer type, int pageIndex, int pageSize) {
        QueryWrapper<TActOrder> wrapper = new QueryWrapper();
        wrapper.eq("CLIENT_ID", userId);
        if (type!=null)wrapper.eq("PAY_TYPE",type);
        IPage<TActOrder> lists = mapper.selectPage(new Page<TActOrder>(pageIndex, pageSize), wrapper);
        return lists;
    }

    public IPage<TActOrder> getOrderListByOpenId(String openId, String type, int pageIndex, int pageSize){
        QueryWrapper<TActOrder> wrapper = new QueryWrapper();
        wrapper.eq("OPEN_ID", openId);
        log.info("type = " + type);
        if (type != null) {
            if(type.equals("1")) {
                wrapper.eq("OR_STATUS", "TRADE_SUCCESS");
                wrapper.isNull("HX_TIME");
                //wrapper.and(wrapper -> wrapper.isNull("HX_TIME"));
            }else if(type.equals("2")) {
                wrapper.eq("OR_STATUS", "TRADE_SUCCESS");
                wrapper.isNotNull("HX_TIME");
                //wrapper.and(wrapper -> wrapper.isNotNull("HX_TIME"));
            }
        }
        wrapper.orderByDesc("CREATE_TIME");
        IPage<TActOrder> lists = mapper.selectPage(new Page<TActOrder>(pageIndex, pageSize), wrapper);
        //log.info(lists.toString());
        return lists;
    }

}
